package com.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.boot.DTO.DishDAO;
import com.boot.Vo.DishVo;
import com.boot.interceptor.BusinessException;
import com.boot.mapper.DishFlavorMapper;
import com.boot.mapper.SetmealDishMapper;
import com.boot.pojo.Dish;
import com.boot.pojo.DishFlavor;
import com.boot.pojo.SetmealDish;
import com.boot.result.Result;
import com.boot.result.ResultCodeNum;
import com.boot.service.DishFlavorService;
import com.boot.service.DishService;
import com.boot.mapper.DishMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @author liyan
 * @description 针对表【dish(菜品)】的数据库操作Service实现
 * @createDate 2025-04-17 15:50:40
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish>
        implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Override
    @Transactional
    public Result saveWithFlavor(DishDAO dishDAO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDAO, dish);
        dish.setStatus(1);
        int insertRow = dishMapper.insert(dish);
        if (insertRow == 0) {
            throw new BusinessException("insert error x1", ResultCodeNum.INSERT_ERROR);
        }
        if (dish.getId() == null) {
            throw new BusinessException("insert error x2", ResultCodeNum.INSERT_ERROR);
        }
        List<DishFlavor> flavors = dishDAO.getFlavors();
        if (CollectionUtils.isNotEmpty(flavors)) {
            flavors.forEach(f -> f.setDishId(dish.getId()));
            if (!dishFlavorService.saveBatch(flavors)) {
                throw new BusinessException("insert error x3", ResultCodeNum.INSERT_ERROR);
            }
        }
        return Result.success();
    }

    @Override
    public Result queryDishList(DishVo dishVo) {
        IPage<Dish> myPage = new Page<>(dishVo.getPage(), dishVo.getPageSize());
        dishMapper.selectDishList(myPage, dishVo);
        List<Dish> list = myPage.getRecords();
        System.out.println(list);
        Long total = myPage.getTotal();
        return Result.success(Map.of("total", total, "records", list));
    }

    @Override
    public Result findById(Long id) {
        DishDAO dish = dishMapper.findById(id);
        return Result.success(dish);
    }

    @Override
    public Result findByCategory(Long categoryId) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId, categoryId);
        List<Dish> dishList = dishMapper.selectList(queryWrapper);
        return Result.success(dishList);
    }

    @Override
    public Result deleteByIds(List<Long> ids) {
        LambdaQueryWrapper<Dish> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.in(Dish::getId, ids)
                .eq(Dish::getStatus, 1);
        Long enableNum = dishMapper.selectCount(wrapper1);
        if (enableNum > 0) {
            throw new BusinessException("have dish on sale", ResultCodeNum.DELETE_ERROR);
        }
        LambdaQueryWrapper<SetmealDish> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.in(SetmealDish::getDishId, ids);
        Long setmealDishNum = setmealDishMapper.selectCount(wrapper2);
        if (setmealDishNum > 0) {
            throw new BusinessException("dish associated by setmeal", ResultCodeNum.DELETE_ERROR);
        }
        int deleteNum = dishMapper.deleteBatchIds(ids);
        if (deleteNum != ids.size()) {
            throw new BusinessException("delete error", ResultCodeNum.DELETE_ERROR);
        }
        LambdaQueryWrapper<DishFlavor> wrapper3 = new LambdaQueryWrapper<>();
        wrapper3.in(DishFlavor::getDishId, ids);
        dishFlavorMapper.delete(wrapper3);
        return Result.success();
    }

    @Override
    public Result updateStatus(Integer id, Integer status) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getId, id)
                .ne(Dish::getStatus, status);
        Dish dish = dishMapper.selectOne(queryWrapper);
        if (dish == null) {
            return Result.build(null, ResultCodeNum.CHANGE_SALE_STATUS_ERROR);
        }
        LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Dish::getId, id)
                .set(Dish::getStatus, status);
        int updateRow = dishMapper.update(dish, updateWrapper);
        if (updateRow == 0) {
            return Result.build(null, ResultCodeNum.CHANGE_SALE_STATUS_ERROR);
        }
        return Result.success();

    }

    @Override
    @Transactional
    public Result updateDish(DishDAO dishDAO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDAO, dish, new String[]{"categoryName", "flavors"});
        List<DishFlavor> dishFlavors = dishDAO.getFlavors();
        int updateRow = dishMapper.updateById(dish);
        if (updateRow == 0) {
            return Result.build(null, ResultCodeNum.UPDATE_DISH_ERROR);
        }
        LambdaUpdateWrapper<DishFlavor> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(DishFlavor::getDishId, dish.getId());
        dishFlavorMapper.delete(updateWrapper);
        if (!dishFlavors.isEmpty()) {
            dishFlavors.forEach(df -> df.setDishId(dish.getId()));
            if(!dishFlavorService.saveBatch(dishFlavors)) {
                throw new BusinessException("dishFlavors save error", ResultCodeNum.UPDATE_DISH_ERROR);
            }
            return Result.success();
        }
        return Result.success();

    }
}




